import WordsReader from '../utils/WordsReader';
import ToolKit from '../utils/ToolKit';


export default class NameGenerator {

    /**
     * 构建名字生成器
     * @param gender 性别，1:男,2:女
     * @param wordCount 名字字数
     */
    constructor(gender, wordCount) {
        this.gender = gender;
        this.wordCount = wordCount;
    }

    /**
     * 生成一串名字
     * @param count 生成数量
     */
    genNames = (count) => {
        const fileList = [];
        if(this.gender === 1){          //男性
            fileList.push('name-male-1.txt');
            fileList.push('name-male-2.txt');
        }else if(this.gender === 2){    //女性
            fileList.push('name-female-1.txt');
            fileList.push('name-female-1.txt');
        }else{                          //不限性别
            fileList.push('name-male-1.txt');
            fileList.push('name-male-2.txt');
            fileList.push('name-female-1.txt');
            fileList.push('name-female-1.txt');
        }


        return new Promise((resolve, reject) => {
            Promise.all(fileList.map(f => WordsReader.readWords(f)))
                .then((wordsListArray) => {
                    //数组合并
                    let wordsList = [];
                    wordsListArray.forEach((itemArray,key,wholeArray) => {
                        wordsList = wordsList.concat(itemArray);
                    });

                    const retList = [];
                    for (let i = 0; i < count; i++) {
                        const randomIndex = ToolKit.randomNumber(wordsList.length - 1); //在长度范围内随机取数
                        const words = wordsList[randomIndex];

                        if(this.wordCount > 0) {
                            if(words.length === this.wordCount){
                                retList.push(words);
                            }else{      //字数不满足，则忽略他
                                i--;
                            }
                        }else{
                            retList.push(words);
                        }
                    }
                    resolve(retList);
                }).catch((e) => {
                reject(e);
            });
        });
    }
}
